<script setup lang="ts">
import { ref, computed } from 'vue';
import CKEditor from '@ckeditor/ckeditor5-vue';
import ClassicEditor from '@ckeditor/ckeditor5-build-classic';
import uploadImage from '@/utils/uploadImage';

const props = withDefaults(defineProps<{ modelValue: string }>(), { modelValue: '' });

const emit = defineEmits<{
  (e: 'update:model-value', value: string): void;
}>();

const ckeditor = CKEditor.component;

class MyUploadAdapter {
  loader: any;
  constructor(loader: any) {
    this.loader = loader;
  }
  // 启动上传过程
  upload() {
    return this.loader.file.then(
      (file: File) =>
        new Promise((resolve, reject) => {
          uploadImage(file)
            .then((res) => {
              resolve({ default: res?.data.url });
            })
            .catch(reject);
        })
    );
  }
  // 终止上传钩子
  abort() {}
}

function MyCustomUploadAdapterPlugin(editor: any) {
  editor.plugins.get('FileRepository').createUploadAdapter = (loader: any) => {
    return new MyUploadAdapter(loader);
  };
}

const editor = ref(ClassicEditor);
const editorData = computed({
  get() {
    return props.modelValue;
  },
  set(newValue) {
    emit('update:model-value', newValue);
  },
});
const editorConfig = ref({
  removePlugins: ['Heading'],
  extraPlugins: [MyCustomUploadAdapterPlugin],
  placeholder: '请输入商品详情',
});
</script>
<template>
  <div class="editor">
    <ckeditor :editor="editor" v-model="editorData" :config="editorConfig"></ckeditor>
  </div>
</template>
<style lang="less" scoped>
.editor {
  :deep(.ck-editor__editable_inline:not(.ck-comment__input *)) {
    height: 300px;
    overflow-y: auto;
  }
}
</style>
